module top_module (
    input clk,
    input reset,      // Synchronous reset
    input data,
    output [3:0] count,
    output counting,
    output done,
    input ack );
	
	localparam IDLE=4'b0000;
	localparam S1=4'b0001;//1
	localparam S2=4'b0010;//11
	localparam S3=4'b0011;//110
	localparam S4=4'b0100;//1101,
	localparam S5=4'b0101;//1101,
	localparam S6=4'b0110;//1101,
	localparam S7=4'b0111;//1101,
	localparam S8=4'b1000;//1101,counting
	localparam S9=4'b1001;//1101,wait
	
	reg [3:0]state;
	reg [3:0]next_state;
	always@(posedge clk)begin
		if(reset)begin
			state<=IDLE;
		end
		else begin
			state<=next_state;
		end
	end
	reg [3:0]count_r;
	always@(*)begin
		case(state)
			IDLE:begin//*
				next_state=(data)?S1:IDLE;
				count_r=4'h0;
				cout_s=1'b0;
			end
			S1:begin//1
				next_state=(data)?S2:IDLE;
				count_r=4'h0;
				cout_s=1'b0;
			end
			S2:begin//11
				next_state=(data)?S2:S3;
				count_r=4'h0;
				cout_s=1'b0;
			end
			S3:begin//110
				next_state=(data)?S4:IDLE;
				count_r=4'h0;
				cout_s=1'b0;
			end
			S4:begin//1101,next_state=S5
				next_state=S5;
				count_r[3]=data;
				count_r[2:0]=count_r[2:0];
				cout_s=1'b0;
			end
			S5:begin
				next_state=S6;
				count_r[2]=data;
				count_r[1:0]=count_r[1:0];
				count_r[3]=count_r[3];
				cout_s=1'b0;
			end
			S6:begin//done=1
				next_state=S7;
				count_r[1]=data;
				count_r[0]=count_r[0];
				count_r[3:2]=count_r[3:2];
				cout_s=1'b0;
			end
			S7:begin//1101,next_state=S8
				next_state=S8;
				count_r[0]=data;
				count_r[3:1]=count_r[3:1];
				cout_s=1'b0;
			end
			S8:begin//1101,counting
				next_state=(cout_rs==14'd999&cout_rm==count_r)?S9:S8;
				count_r=count_r;
				cout_s=1'b1;
			end
			S9:begin
				next_state=(ack)?IDLE:S9;
				count_r=4'h0;
				cout_s=1'b0;
			end
			default:begin
				next_state=next_state;
				count_r=4'h0;
				cout_s=1'b0;
			end
		endcase
	end
	
	reg cout_s;
	reg[13:0]cout_rs;
	reg[3:0]cout_rm;
	always@(posedge clk)begin
		if(reset)begin
			cout_rs<=14'd0;
			cout_rm<=4'h0;
		end
		else begin
			if(cout_s)
			begin
				if(cout_rs<14'd999)begin
					cout_rs<=cout_rs+14'h1;
					cout_rm<=cout_rm;
				end
				else begin
					cout_rs<=14'h0;
					cout_rm<=cout_rm+4'h1;
				end
			end
			else begin
				cout_rs<=14'h0;
				cout_rm<=4'h0;
			end
		end
	end
	
	assign count=(state==S8)?(count_r-cout_rm):1'b0;
    assign counting=cout_s;
    assign done=state==S9;

endmodule